package com.ywz.framework.security.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ywz.common.ResultResp;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 类描述 -> 授权失败处理类
 *
 * @Author: ywz
 * @Date: 2024/07/28
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    /**
     * 方法描述 -> 授权失败处理
     *
     * @Author: ywz
     * @Date: 2024/07/28
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        result.put("data", "没有相应的权限");
        result.put("code", ResultResp.UNAUTHORIZED_CODE);
        String s = new ObjectMapper().writeValueAsString(result);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(s.getBytes(StandardCharsets.UTF_8));
        outputStream.close();
    }
}